package com.lack.openapigateway;

import com.lack.openApiClientSdk.utils.SignUtil;
import com.lack.openApicommon.model.entity.InterfaceInfo;
import com.lack.openApicommon.model.entity.User;
import com.lack.openApicommon.model.entity.UserInterfaceInfo;
import com.lack.openApicommon.service.InnerInterfaceInfoService;
import com.lack.openApicommon.service.InnerUserInterfaceInfoService;
import com.lack.openApicommon.service.InnerUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import static java.util.Arrays.asList;

/**
 * 全局过滤器
 */
@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @DubboReference
    private InnerUserService innerUserService;
    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;
    @DubboReference
    private InnerUserInterfaceInfoService innerUserInfoService;
    //白名单
    private static final List<String> IP_WHITE_lIST = asList("127.0.0.1", "localhost");
    private static final String INSERT_HOST = "localhost://8081";


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.打印日志


        ServerHttpRequest request = exchange.getRequest();
        String path = INSERT_HOST + request.getPath().value();
        String method = request.getMethod().toString();
        log.info("请求标识:{}", request.getId());
        log.info("请求路径:{}", path);
        log.info("请求方法:{}", method);
        log.info("请求参数:{}", request.getQueryParams());
        log.info("请求来源:{}", request.getRemoteAddress());
        log.info("请求头:{}", request.getHeaders());
        String formUrl = request.getLocalAddress().getHostString();
        log.info("请来源地址:{}", formUrl);
        //2.黑白名单
        ServerHttpResponse response = exchange.getResponse();
        if (!IP_WHITE_lIST.contains(formUrl)) {
            return handelNoAuth(response);
        }
        //3.用户鉴权
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String body = headers.getFirst("body");
        String nonce = headers.getFirst("nonce");
        String timeStamp = headers.getFirst("timeStamp");
        String sign = headers.getFirst("sign");
        User invokeUser = null;
        try {
            invokeUser = innerUserService.getInvokeUser(accessKey);

        } catch (Exception e) {
            log.error("get invokeUser error", e);
        }
        Long userId = invokeUser.getId();
        if (invokeUser == null) {
            return handelNoAuth(response);
        }

        if (nonce.length() > 5) {
            return handelNoAuth(response);
        }

        Long currentTimeMillis = System.currentTimeMillis() / 1000;

        final Long Time = 60 * 5L;
        if ((currentTimeMillis - Long.parseLong(timeStamp)) >= Time) {
            return handelNoAuth(response);
        }
        String secretKey = invokeUser.getSecretKey();
        String genSign = SignUtil.genSign(body, secretKey);
        if (genSign == null || !sign.equals(genSign)) {
            return handelNoAuth(response);
        }
        //4.判断接口是否存在从数据库中查询校验参数
        InterfaceInfo interfaceInfo = null;
        try {
            interfaceInfo = innerInterfaceInfoService.getInterfaceInfo(path, method);
        } catch (Exception e) {
            log.error("get interfaceInfo error", e);
        }
        if (interfaceInfo == null) {
            return handelNoAuth(response);
        }
        Long interfaceInfoId = interfaceInfo.getId();
        //5.判断用户是否还有调用次数
        UserInterfaceInfo userInterfaceInfo = innerUserInfoService.getUserInterfaceInfo(interfaceInfoId, userId);
        Integer leftNum = userInterfaceInfo.getLeftNum();
        if (leftNum <= 0){
            return handelNoAuth(response);
        }
        // 6.请求转发+响应日志
//        Mono<Void> filter = chain.filter(exchange);

        return handleResponse(exchange, chain, interfaceInfoId, userId);

//        if (response.getStatusCode() == HttpStatus.OK) {
//
//        } else {
//            //8.调用失败，返回
//            return handelInvokeError(response);
//        }
//        log.info("使用到了过滤器");
//        return filter;
    }

    /**
     * 处理响应
     *
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain, Long interfaceInfoId, Long userId) {
        try {
            // 获取原始的响应对象
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 获取数据缓冲工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 获取响应的状态码
            HttpStatus statusCode = originalResponse.getStatusCode();

            // 判断状态码是否为200 OK(按道理来说,现在没有调用,是拿不到响应码的,对这个保持怀疑 沉思.jpg)
            if (statusCode == HttpStatus.OK) {
                // 创建一个装饰后的响应对象(开始穿装备，增强能力)
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {

                    // 重写writeWith方法，用于处理响应体的数据
                    // 这段方法就是只要当我们的模拟接口调用完成之后,等它返回结果，
                    // 就会调用writeWith方法,我们就能根据响应结果做一些自己的处理
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        // 判断响应体是否是Flux类型
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 返回一个处理后的响应体
                            // (这里就理解为它在拼接字符串,它把缓冲区的数据取出来，一点一点拼接好)
                            return super.writeWith(fluxBody.map(dataBuffer -> {
                                // 7.调用成功，调用次数+1
                                try {
                                    innerUserInfoService.invokeCount(interfaceInfoId,userId);
                                } catch (Exception e) {
                                    log.error("invokeCount error", e);
                                }
                                // 读取响应体的内容并转换为字节数组
                                byte[] content = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(content);
                                DataBufferUtils.release(dataBuffer);//释放掉内存
                                // 构建日志
                                StringBuilder sb2 = new StringBuilder(200);
                                sb2.append("<--- {} {} \n");
                                List<Object> rspArgs = new ArrayList<>();
                                rspArgs.add(originalResponse.getStatusCode());
                                //rspArgs.add(requestUrl);
                                String data = new String(content, StandardCharsets.UTF_8);//data
                                sb2.append(data);
                                log.info(sb2.toString(), rspArgs.toArray());//log.info("<-- {} {}\n", originalResponse.getStatusCode(), data);
                                // 将处理后的内容重新包装成DataBuffer并返回
                                return bufferFactory.wrap(content);
                            }));
                        } else {
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 对于200 OK的请求,将装饰后的响应对象传递给下一个过滤器链,并继续处理(设置repsonse对象为装饰过的)
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            // 对于非200 OK的请求，直接返回，进行降级处理
            return chain.filter(exchange);
        } catch (Exception e) {
            // 处理异常情况，记录错误日志
            log.error("gateway log exception.\n" + e);
            return chain.filter(exchange);
        }
    }




    public Mono<Void> handelNoAuth(ServerHttpResponse response) {
        // 设置响应状态码为禁止访问(403 Forbidden)
        response.setStatusCode(HttpStatus.FORBIDDEN);
        // 完成响应并返回
        Mono<Void> voidMono = response.setComplete();
        return voidMono;
    }

    public Mono<Void> handelInvokeError(ServerHttpResponse response) {
        // 设置响应状态码为禁止访问(403 Forbidden)
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        // 完成响应并返回
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return -1;
    }
}